/*
 * MIT License
 *
 * Copyright (c) 2025 Mark·虎
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package com.hsxxherp.key.support.i18n.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hsxxherp.key.common.error.ErrorCode;
import com.hsxxherp.key.common.exception.BusinessException;
import com.hsxxherp.key.support.i18n.mapper.I18nResourceTemplateMapper;
import com.hsxxherp.key.support.i18n.model.entity.I18nLocale;
import com.hsxxherp.key.support.i18n.model.entity.I18nResource;
import com.hsxxherp.key.support.i18n.model.entity.I18nResourceTemplate;
import com.hsxxherp.key.support.i18n.service.II18nResourceTemplateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class I18nResourceTemplateServiceImpl extends ServiceImpl<I18nResourceTemplateMapper, I18nResourceTemplate> implements II18nResourceTemplateService<I18nResourceTemplate> {

    private static final Logger logger = LoggerFactory.getLogger(I18nResourceTemplateServiceImpl.class);

    I18nLocaleServiceImpl i18nLocaleService;

    I18nResourceServiceImpl i18nResourceService;

    public I18nResourceTemplateServiceImpl(I18nLocaleServiceImpl i18nLocaleService, I18nResourceServiceImpl i18nResourceService) {
        this.i18nLocaleService = i18nLocaleService;
        this.i18nResourceService = i18nResourceService;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public I18nResourceTemplate registerResourceTemplate(I18nResourceTemplate template) {
        // 检查资源模板是否已存在
        if (isResourceTemplateExists(template)) {
            logger.error("资源模板已存在，无法注册，模板信息：{}", template);
            throw new BusinessException("资源模板已存在，无法注册").setCode(ErrorCode.FAIL);
        }
        try {
            // 插入资源模板到数据库
            baseMapper.insert(template);
            logger.info("资源模板注册成功，模板信息：{}", template);
            // 发布资源模版
            List<I18nLocale> i18nLocales = i18nLocaleService.getAllLocales();

            for (I18nLocale i18nLocale : i18nLocales) {
                I18nResource i18nResource = new I18nResource();
                i18nResource.setLocaleId(i18nLocale.getId());
                i18nResource.setTemplateId(template.getId());
                i18nResource.setMessage(template.getDefaultMessage());

                i18nResourceService.save(i18nResource);
            }

            return template;
        } catch (Exception e) {
            logger.error("资源模板注册失败，模板信息：{}", template, e);
            throw new BusinessException("资源模板注册失败", e).setCode(ErrorCode.FAIL);
        }
    }

    @Override
    public List<I18nResourceTemplate> getAllResourceTemplates() {
        try {
            List<I18nResourceTemplate> templates = baseMapper.selectList(null);
            logger.info("获取到 {} 个资源模板", templates.size());
            return templates;
        } catch (Exception e) {
            logger.error("获取所有资源模板失败", e);
            throw new BusinessException("获取所有资源模板失败", e).setCode(ErrorCode.FAIL);
        }
    }

    /**
     * 检查资源模板是否已存在
     *
     * @param template 资源模板对象
     * @return 如果存在返回 true，否则返回 false
     */
    private boolean isResourceTemplateExists(I18nResourceTemplate template) {
        QueryWrapper<I18nResourceTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("resource_code", template.getResourceCode());
        return this.count(queryWrapper) > 0;
    }
}